package com.fast.admin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fast.admin.service.UserService;
import com.fast.common.db.mapper.UserMapper;
import com.fast.common.db.mapper.po.User;
import com.fast.common.pojo.AuthUser;
import com.fast.common.pojo.req.admin.UserReq;
import com.fast.common.redis.RedisClient;
import com.fast.common.utils.AuthUtils;
import com.fast.common.utils.PropertiesUtil;
import com.fast.common.web.exception.AuthException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author TWL
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2024-06-15 14:09:25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private AuthUtils authUtils;

    @Override
    public String login(UserReq userReq) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, userReq.getUsername()).eq(User::getPassword, userReq.getPassword()));
        if (user == null) {
            throw new AuthException("账号密码错误");
        }
        String token = authUtils.build(user.getId());
        AuthUser copy = PropertiesUtil.copy(user, AuthUser.class);
        copy.setToken(token);
        redisClient.set(authUtils.getAccessTokenKey(user.getId()), copy, authUtils.getExpiration(), TimeUnit.SECONDS);

        return token;
    }

    @Override
    public void loginOut() {

    }
}




